package com.jason.exp.api;

import com.google.common.collect.Maps;
import com.jason.exp.entity.User;
import com.jason.exp.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.Validator;
import java.util.Map;

/**
 * Created by fuyongde on 2016/8/31.
 */
@RestController
@RequestMapping(value = "/api/users")
public class UserRestController {

    @Autowired
    private UserService userService;
    @Autowired
    private Validator validator;

    @RequestMapping(value = "/{userId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public User getUserById(
            @PathVariable String userId
    ) {
        User result = userService.findById(userId);
        return result;
    }

    @RequestMapping(method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public User registerUser(@Valid User user, BindingResult results) {
        BeanValidators.validateWithException(validator, user);
        User result = userService.registerUser(user);
        return result;
    }

    @RequestMapping(value = "/isExist", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public Map<String, Object> isExist(
            @RequestParam(name = "username") String username
    ) {
        boolean isExist = userService.isExist(username);
        Map<String, Object> result = Maps.newHashMap();
        Boolean b = new Boolean(isExist);
        result.put("isExist", b);
        return result;
    }

    @RequestMapping(value = "/{userId}/activateUser", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public Map<String, Object> activateUser(
            @PathVariable String userId,
            @RequestParam(name = "email") String email
    ) {
        userService.sendActivateMail(userId, email);
        Map<String, Object> result = Maps.newHashMap();
        result.put("activateUser", Boolean.TRUE);
        return result;
    }

    @RequestMapping(value = "/{userId}/activateUser", method = RequestMethod.PUT, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public Map<String, Object> activateUser(
            @PathVariable String userId,
            @RequestParam(name = "code") Integer code
    ) {
        userService.activateUser(userId, code);
        Map<String, Object> result = Maps.newHashMap();
        result.put("activateUser", Boolean.TRUE);
        return result;
    }
}
